import { Request, Response } from "express";
import "reflect-metadata";
import { Autowired, Singleton, get, Controller, post } from "../decorator";
import { UserServiceInter } from "../service";
import { getSession } from "../utils/sessionUtil";
import type { UserInfo } from "../entity/UserInfo";

@Controller("/")
class UserController {
  @Autowired("userServiceImpl") //  Inject
  @Singleton(true)
  private userServiceImpl!: UserServiceInter;

  @get("/")
  index(req: Request, res: Response): void {
    const session: any = getSession(req);
    // console.log(session);
    if (session.userInfo) {
      let htmlstr = `<div><a href='/searchFoodHistory'
       style='text-decoration:none;color:red'> 搜索美食历史信息 </a></div><div><a href = '/orderInfo'  style='text-decoration:none;color:red'> 订单信息 </a></div><div><a href="/loginout" style='text-decoration:none;color:red'>注销</a></div>`;
      res.send(htmlstr);
    } else {
      res.redirect("/login");
    }
  }

  @get("/login")
  login(req: Request, res: Response): void {
    let htmlstr = `
    <div>
      <form method="post" action="/loginProcess">
        <div>用户名: <input type='text' name='username'/> </div>
        <div>密码: <input type='password' name='pwd'/> </div>
        <div><input type="submit" value="提交" /> </div>
      </form>
    </div>`;

    res.send(htmlstr);
  }

  @post("/loginProcess")
  public loginProcess(req: Request, res: Response): void {
    const session: any = getSession(req);
    /* const UserServiceImpl = Reflect.getOwnPropertyDescriptor(
      UserController.prototype,
      "userServiceImpl"
    )?.value; */
    const UserServiceImpl: any = UserController.prototype.userServiceImpl;

    const user: UserInfo = UserServiceImpl.login(
      req.body.username,
      req.body.pwd
    );
    if (user?.username) {
      session.userInfo = user;
      res.setHeader("Content-Type", "text/html;charset=UTF-8");
      let outputHtml = "";
      if (user.role === "admin") {
        outputHtml += `<div>管理员:${user.role}</div>`;
        outputHtml += `<div><a href="/authorityManage">进入管理员权限页面</a></div>`;
      }
      res.write(outputHtml);
      res.write(`<div>登录成功,欢迎你:${user.username}</div>`);
      res.write(`<div><a href="/">进入首页</a></div>`);
      res.write(
        `<div><a href="/showFood/tudousi/beijing">进入美食首页</a></div>`
      );
      res.end();
    } else {
      res.setHeader("Content-Type", "text/html;charset=UTF-8");
      res.write(`<div><a>账号或密码错误</a></div>`);
      res.end();
    }
  }
}

export {};
